package modules.communication
{
	import flash.events.NetStatusEvent;
	import flash.net.NetConnection;
	
	import modules.GameEvent;
	import modules.MuduleManager;
	import modules.login.Login;

	public class CommunicationManager extends MuduleManager
	{
		private var netConnection:NetConnection;

		private var msgSender:MsgSender;

		private var msgReceiver:MsgReceiver;

		public function CommunicationManager()
		{
			init();
		}

		override public function init():void
		{
			netConnection = new NetConnection();

			msgSender = new MsgSender(netConnection);

			msgReceiver = new MsgReceiver(netConnection);

			dispatcher.addEventListener(CommunicationEvent.CONNECT_REQ, onGameEvent);
			dispatcher.addEventListener(CommunicationEvent.DISCONNECT_REQ, onGameEvent);
			
			netConnection.addEventListener(NetStatusEvent.NET_STATUS, onNetStatusHandler);
		}
		
		protected function onGameEvent(event:GameEvent):void
		{
			switch(event.type)
			{
				case CommunicationEvent.CONNECT_REQ:
					netConnection.connect(event.data.connectPath);
					break;
				case CommunicationEvent.DISCONNECT_REQ:
					netConnection.close();
					break;
			}
		}

		protected function onNetStatusHandler(event:NetStatusEvent):void
		{
			logger(event.info);
			switch (event.info.code)
			{
				case "NetConnection.Connect.Success":
					Communication.connecting = true;
					dispatcher.dispatchEvent(new CommunicationEvent(CommunicationEvent.CONNECT_ACK));
					break;
				case "NetConnection.Connect.Closed":
					Communication.connecting = false;
					Login.logined = false;
					dispatcher.dispatchEvent(new CommunicationEvent(CommunicationEvent.DISCONNECT_ACK));
					break;
				
			}
		}

	}
}
